package com.czx.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.czx.common.constants.CookieKey;
import com.czx.common.constants.RedisKeys;
import com.czx.dto.ResetPwdDto;
import com.czx.entity.OldPassword;
import com.czx.entity.User;
import com.czx.common.security.UserTokenThreadLocal;
import com.czx.service.LikeService;
import com.czx.service.RegisterService;
import com.czx.service.UserService;
import com.czx.common.utils.R;
import com.czx.vo.UserToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;


@Controller
public class UserController {
    @Autowired
    private RegisterService registerService;
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private LikeService likeService;



    @RequestMapping("/sendEmailCodeForResetPwd")
    @ResponseBody
    public R sendEmailCodeForResetPwd(String username){
        R r = userService.sendEmailCodeForResetPwd(username);
        return r;
    }


    //重置密码
    @RequestMapping("/resetPwd")
    @ResponseBody
    public R resetPwd(ResetPwdDto resetPwdDto) {
        R r = userService.resetPwd(resetPwdDto);
        return r;
    }

    //个人主页
    @RequestMapping("/info")
    public String info(Integer id, Model model) {

        UserToken userToken = UserTokenThreadLocal.get();
        ZSetOperations<String, String> zset = stringRedisTemplate.opsForZSet();
        //粉丝的key
        String fansKey = String.format(RedisKeys.USER_FANS_KEY, id);
        //关注的key
        String followKey = String.format(RedisKeys.USER_FOLLOWER_KEY, id);
        //目标的key
        String targetKey = String.format(RedisKeys.USER_TARGET_KEY, id);


        //查看目标用户的key下有没有当前用户的key
        Double score = zset.score(fansKey, userToken.getUser().getId().toString());
        if (score != null) {
            model.addAttribute("hasFollowed", true);
        } else {
            model.addAttribute("hasFollowed", false);
        }
        //获取关注的人的数量
        String targetCount = stringRedisTemplate.opsForValue().get(targetKey);
        //获取关注人的数量
        Long followCount = stringRedisTemplate.opsForZSet().size(followKey);
        if (targetCount == null) {
            targetCount = "0";
        }
        model.addAttribute("followerCount", followCount);
        model.addAttribute("fansCount", targetCount);

        //获取点赞数量
        //点赞用户的key
        //准备用户点赞数量的key
        String userLikeKey = String.format(RedisKeys.USER_LIKE_KEY, CookieKey.USER, userToken.getUser().getId());
        String userLikeCount = stringRedisTemplate.opsForValue().get(userLikeKey);
        if (userLikeCount == null) {
            userLikeCount = "0";
        }
        model.addAttribute("userLikeCount", userLikeCount);
        //获取主页信息
        User user = userService.getInfoById(id);
        model.addAttribute("user", user);
        return "site/profile";
    }

    //个人信息
    @RequestMapping("/profile")
    public String profile(Integer id, Model model) {
        User user = userService.getUserById(id);
        model.addAttribute("user", user);
        return "site/profile";
    }

    @RequestMapping("/login")
    @ResponseBody
    //把前端传递的JSON字符串，给我格式化到Map中
    public R login(@RequestBody Map<String, String> param, HttpServletResponse response) {
        //获取前端表单数据
        String username = param.get("username");
        String password = param.get("password");
        //验证
        if (ObjectUtils.isEmpty(username)) {
            return R.fail("用户名不能为空");
        }
        if (ObjectUtils.isEmpty(password)) {
            return R.fail("密码不能为空");
        }
        //调用业务层实现登录
        UserToken userToken = userService.login(username, password);
        //获取到后端数据
        //把UUID写入浏览器的Cookie中
        Cookie cookie = new Cookie(CookieKey.LOGIN_COOKIE_KEY, userToken.getUuid());
        // cookie.setDomain(); // 默认就是当前域名
        cookie.setPath("/");
        cookie.setMaxAge(60 * 30 * 1000); // 设置过期时间
        response.addCookie(cookie);
        return R.success();
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        // 清除Cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                cookie.setValue("");
                cookie.setPath("/");
                cookie.setMaxAge(0);
                response.addCookie(cookie);
            }
        }
        return "redirect:/";
    }

    @RequestMapping("/password")
    @ResponseBody
    public R updatePassword(HttpSession session, @RequestBody OldPassword oldPassword) {

        System.out.println(oldPassword + "1");
        User user = (User) session.getAttribute("loginUser");

        Integer integer = userService.updatePassword(oldPassword, user);

        System.out.println(integer);
        if (integer != 0) {
            return R.success();
        }
        return R.fail();
    }


    @RequestMapping("/active")
    public String active(String code, Model model) {
        QueryWrapper<User> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("activation_code", code);
        User user = registerService.getOne(objectQueryWrapper);
        if (user.getStatus() == 0) {
            user.setStatus(1);
            registerService.updateById(user);
            model.addAttribute("activeMSG", "激活成功");

        } else {
            model.addAttribute("activeMSG", "该账号已激活");
        }

        return "site/login";
    }

    @RequestMapping("/register")
    @ResponseBody
    public R doRegister(@RequestBody User user) {
        userService.doRegister(user);
        return R.success();

    }

}
